import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store';
import '@/assets/css/index.scss'; // 全局自定义的css样式
import Vuex from 'vuex';
import {
    Utils
} from '@/utils/utils.js';

import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, {
    preLoad: 2,
    loading: require('./assets/img/loading.gif'),
    error: require('./assets/img/error.jpg'),
    attempt: 1
});
// 引入全局自定义组件 ==开始
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css';
import 'vue-awesome/icons';
import Icon from 'vue-awesome/components/Icon';

Vue.component('v-icon', Icon);
Vue.config.productionTip = false;
Vue.use(ElementUI);
// 引入全局自定义组件 ==结束
// 全局路由钩子初始化 ==>开始
const authwhiteList = ['/login', '/sendpwd', '/reset', '/404', '/401']; // 免登陆路由白名单
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css'; // Progress 进度条 样式
router.beforeEach((to, from, next) => {
    NProgress.start(); // 开启Progress
    // 不用登陆的界面
    let token = Utils.GetLocalData('zillionossjwt');
    if (authwhiteList.indexOf(to.path) >= 0) {
        if (to.path === '/login') {
            if (token) {
                // console.log('目标路由为login,即将跳转Index...');
                next({
                    path: '/'
                });
                NProgress.done();
            } else {
                next();
                NProgress.done();
            }
        } else {
            // console.log(to.path + '无需登录,跳转中...');
            next();
            NProgress.done();
        }
    } else {
        if (token) {
            // console.log('检测到Token为' + token);
            // vuex授权缓存全局动态路由
            if (store.getters.authRouters && store.getters.userInfo.userid) {
                // console.log('检测到authRouters数量为' + store.getters.authRouters.length);
                if (store.getters.authRouterPaths.indexOf(to.path) >= 0) {
                    // console.log('找到授权路由,即将跳转' + to.path);
                    next();
                    NProgress.done();
                } else {
                    console.log(to.path + '路由未授权,即将跳转401...');
                    next({
                        path: '/401',
                        query: {
                            noGoBack: true
                        }
                    });
                    NProgress.done();
                }
            } else {
                // vuex 无路由授权信息,需要重新从服务器获取路由
                store.dispatch('GetLoginUser').then(res => {
                    // console.log('vuex 无路由授权信息,从服务器获得路由');
                    if (store.getters.authRouters) {
                        next({...to
                        });
                        NProgress.done(); // hack方法 确保addRoutes已完成
                    } else {
                        // console.log('从服务器获得路由失败,强制登出');
                        store.dispatch('FedLogOut').then(() => {
                            next({
                                path: '/login'
                            });
                            NProgress.done();
                        });
                    }
                }).catch(() => {
                    // console.log('从服务器获得路由失败,强制登出');
                    store.dispatch('FedLogOut').then(() => {
                        next({
                            path: '/login'
                        });
                        NProgress.done();
                    });
                });
            }
        } else {
            // console.log('无token,强制登出');
            store.dispatch('FedLogOut').then(() => {
                next({
                    path: '/login'
                });
                NProgress.done();
            });
        }
    }
});

router.afterEach(() => {
    NProgress.done(); // 结束Progress
});
// 全局路由钩子初始化 ==>结束

// 全局axios配置初始化 ==>开始
import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);
Vue.use(Vuex);
axios.defaults.timeout = 30000; // 30S超时
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = (process.env.NODE_ENV === 'production' ? 'http://123.57.226.114:10005/Api' : 'http://123.57.226.114:8091/Api');
// axios 拦截器
// 加上固定Token 参数
axios.interceptors.request.use((config) => {
    let jwt = Utils.GetLocalData('zillionossjwt');
    if (jwt) {
        let params = config.params;
        if (params) {
            params.token = jwt;
        } else {
            params = {
                token: jwt
            };
        }
        config.params = params;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
    return res;
}, (error) => {
    if (!error.response) {
        ElementUI.Message.error(error.response.status);
        /* router.push({name: 'error'}); */
    } else {
        if (error.response.status === 401) {
            Utils.RemoveLocalData('zillionossjwt');
            ElementUI.Message.error('Jwt验证失败,请重新打开页面!');
            /* router.push({name: 'customerror', query: {errdesc: 'Jwt验证失败,请重新打开页面!'}}); */
        } else {
            if (error.response.status === 404) {
                ElementUI.Message.error(error.response.status);
                /* router.push({name: 'error'}); */
            } else {
                ElementUI.Message.error(error.response);
                /* router.push({name: 'customerror', query: {errdesc: error.message}}); */
            }
        }
    }

    return Promise.reject(error);
});
// 全局axios配置初始化 ==>结束

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store,
    router,
    template: '<App/>',
    components: {
        App
    }
});